package com.example.demo.config;

import com.example.demo.model.Result;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.xml.ws.Action;

/**
 * @className: ResponseAdvice
 * @author: 芃
 * @description: 统一数据返回格式
 * @date: 2024/12/30 11:39
 */
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {

    @Autowired
    private ObjectMapper objectMapper;
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;//返回true表示生效
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //在返回数据之前需要做的事情，对返回的数据进行封装
        if (body instanceof Result){
            return body;
        }
        if (body instanceof String){
            //问题1、如果返回的数据是String类型，则直接返回，不需要封装
            try {
                return objectMapper.writeValueAsString(Result.success(body));
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            //return body;
        }else {
            //如果返回的数据是自定义的对象，则需要封装成Result对象
            return Result.success(body);
        }

    }
}
